let userPool = {}
let lineupList = new Set()
let room = new Set()





module.exports = (server) => {
    const io = require('socket.io')(server,{
        origins: '*:*'
    })
    // socket 就是每一个连接
    io.on('connection', socket => {
        if (+socket.request._query.isService) {
            // 客服
            if (+socket.request._query.reconnect) {
                // 客服重新连接reconnect
                socket.target = socket.request._query.roomNo
                console.log('客服重连', socket.target)
                socket.join(socket.target)
                socket.on('message', msg => {
                    socket.to(socket.target).emit('message',msg)
                })
                socket.on('disconnect', (reason) => {
                    if (reason === 'transport close') {
                        console.log('客服下线reason:', reason)
                        room.delete(socket.target)
                        socket.to(socket.target).emit('service_offline')
                    }
                })
            } else {
                // 客服上线
                socket.target = socket.request._query.roomNo
                console.log('客服', socket.target)
                socket.join(socket.target)
                room.add(socket.target)
                // 排队-1
                autoLineup()
                console.log(room)
                socket.on('message', msg => {
                    socket.to(socket.target).emit('message',msg)
                })
                socket.on('disconnect', (reason) => {
                    if (reason === 'transport close') {
                        console.log('客服下线reason:', reason)
                        room.delete(socket.target)
                        socket.to(socket.target).emit('service_offline')
                    }
                })
            }
        } else {
            // 用户
            if (+socket.request._query.reconnect) {
                // 这里是断开重连的情况
                console.log('用户：这里是断开重连的情况')
                if (!socket.request._query.roomNo) {
                    // 排队中，替换新的socket
                    console.log('排队中，替换新的socket')
                    userPool[socket.request._query.userId] = socket
                } else {
                    // 继续之前的会话
                    console.log('用户：继续之前的会话')
                    socket.target = socket.request._query.roomNo
                    socket.join(socket.target)
                    basic(socket)
                }
            }
            else {
                console.log('排队')
                lineup(socket)
            }
        }
    })
}

// 排队
function lineup(socket) {
    socket.emit('lineup')
    // lineup
    lineupList.add(socket.request._query.userId)
    userPool[socket.request._query.userId] = socket

    console.log('lineupList:',lineupList)
    console.log('userId:', socket.request._query.userId)
    autoLineup()
}
// 基本业务
function basic(socket) {
    // 转发
    socket.on('message', msg => {
        socket.to(socket.target).emit('message', msg)
    })
    // 断开连接时
    socket.on('disconnect', (reason) => {
        if (reason === 'transport close') {
            // 这才是用户退出
            // 将客服room放回客服池中
            socket.target ? room.add(socket.target) : null

            // 删除用户池中的数据
            userPool[socket.request._query.userId] = undefined
            lineupList.delete(socket.request._query.userId)

            console.log(`用户退出: ${reason}`, room)
            // 排队进行
            autoLineup()
            // 通知客服用户已下线
            socket.to(socket.target).emit('user_offline')
        }
    })
}

// 排队业务
function autoLineup() {
    while (room.size && lineupList.size) {
        let tempList = [...lineupList]
        let socket = userPool[tempList[0]]
        
        socket.target = [...room][0]
        room.delete(socket.target)

        // 删除队列
        userPool[tempList[0]] = undefined
        lineupList.delete(tempList[0])
        
        console.log('排队结果',socket.target)

        socket.join(socket.target)  // 加入房间
        socket.to(socket.target).emit('new_client')
        socket.emit('in room', socket.target)
        
        basic(socket)
    }
}